﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Orleans;
using Pay.Admin.App_Start;
using Pay.Common;
using Pay.Configuration;
using Pay.Core;
using Pay.Core.exception;
using Pay.Core.http;
using Pay.Dal;
using Pay.Model;
using Pay.Model.Dto;
using Pay.Model.Enums;
using Pay.Model.Model;
using Pay.Service;
using Pay.Service.user;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Webdiyer.WebControls.Mvc;
namespace Pay.Admin.Controllers
{
    [MyAuthorize]
    public class HomeController : BaseController
    {
        /// <summary>
        /// 主页
        /// </summary>
        /// <returns></returns>
        [MyAuthorize]
        public async Task<ActionResult> Index()
        {
            var service = GrainClient.GrainFactory.GetGrain<IUserSerive>("0");
            var list = await service.GetAllMeun(CurrentUser.Id);
            ViewBag.Menu = list;
            ViewBag.UserName = CurrentUser.UserName;
            return View();
        }

        /// <summary>
        /// 获取平台用户
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, MyAuthorize]
        public async Task<ActionResult> PlatformList(int pageSize = 10, int id = 1)
        {
            var service = GrainClient.GrainFactory.GetGrain<IUserSerive>("0");
            var data = await service.GetUserPage(null, UserType.PlatformNormal, null, null, null, (id - 1) * 10, pageSize);
            var list = new PagedList<UserOutPut>(data.Items, id, pageSize, data.TotalCount);
            return View(list);
        }
        [HttpPost, MyAuthorize]
        public async Task<ActionResult> PlatformList(QueryDto query, int id = 1)
        {
            var user = CurrentUser;
            var service = GrainClient.GrainFactory.GetGrain<IUserSerive>("0");
            ViewBag.Type = CurrentUser.Type;
            var data = await service.GetUserPage(null, UserType.PlatformNormal, query.SearchWord, query.timeBegin, query.timeEnd, (id - 1) * 10, 10);
            var list = new PagedList<UserOutPut>(data.Items, id, 10, data.TotalCount);
            if (Request.IsAjaxRequest())
                return PartialView("_PlatformList", list);
            return View(list);
        }
        /// <summary>
        /// 商家平台用户
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, MyAuthorize]
        public async Task<ActionResult> MerchantList(int pageSize = 10, int id = 1)
        {
            var service = GrainClient.GrainFactory.GetGrain<IUserSerive>("0");
            ViewBag.Type = CurrentUser.Type;
            //判断当前用户角色
            if (CurrentUser.Type == UserType.PlatformNormal || CurrentUser.Type == UserType.PlatformSuper)
            {
                ViewBag.IsShow = true;
                var data = await service.GetUserPage(null, UserType.CustomerSuper, null, null, null, (id - 1) * 10, pageSize);
                var list = new PagedList<UserOutPut>(data.Items, id, pageSize, data.TotalCount);

                return View(list);
            }
            else
            {
                ViewBag.IsShow = false;
                var data = await service.GetUserPage(CurrentUser.MerchantId, UserType.CustomerNormal, null, null, null, (id - 1) * 10, pageSize);
                var list = new PagedList<UserOutPut>(data.Items, id, pageSize, data.TotalCount);
                return View(list);
            }
        }

        /// <summary>
        /// 修改费率
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ActionResult> UpdateFee(long id, string merName)
        {
            var service = GrainClient.GrainFactory.GetGrain<IUserSerive>("0");
            var info = await service.GetMerchantById(id);
            if (info == null) throw new LotException("商户不存在");
            ViewBag.MerchantName = merName;
            return View(info);

        }
        [HttpPost]
        public async Task<ActionResult> UpdateFee(long id, decimal FeeRate)
        {
            var service = GrainClient.GrainFactory.GetGrain<IUserSerive>("0");
            var info = await service.GetMerchantById(id);
            if (info == null) throw new LotException("不存在此用户");
            info.FeeRate = FeeRate;
            await service.UpdateMerchant(info);

            return Json(new { success = true, msg = "更新成功" });

        }

        /// <summary>
        /// 新增商家用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost, MyAuthorize]
        public async Task<ActionResult> AddMerchantUser(UserAddModel user)
        {
            var success = false;
            var msg = "新增失败";
            if (user != null)
            {
                var service = GrainClient.GrainFactory.GetGrain<IUserSerive>("0");
                var model = await service.GetByUserName(user.UserName); if (model != null) return Json(new { success = false, msg = "新增失败，用户名已经存在" });
                if (CurrentUser.Type == UserType.PlatformSuper || CurrentUser.Type == UserType.PlatformNormal)
                {
                    //新增商户表数据
                    var info = new MerchantInfo()
                    {
                        AccessKey = Guid.NewGuid().ToString().Substring(0, 8),
                        CreateTime = DateTime.Now,
                        ExpireTime = DateTime.Now,
                        FeeRate = user.FeeRate,
                        MerchantCode = Guid.NewGuid().ToString().Substring(0, 8),
                         Name=user.UserName
                    };
                    var id = await service.AddMerchantUser(info);
                    user.MerchantId = id;
                    user.type = UserType.CustomerSuper;
                    success = await service.Add(user);
                    msg = "新增成功";
                }
                else
                {
                    //新增子商户
                    user.MerchantId = CurrentUser.MerchantId;
                    user.type = UserType.CustomerNormal;
                    success = await service.Add(user);
                    msg = "新增成功";
                }
            }
            return Json(new { success = success, msg = msg });
        }
        [HttpGet]
        public async Task<ActionResult> AddMerchantUser()
        {
            var service = GrainClient.GrainFactory.GetGrain<IRoleService>("0");
            var role = await service.GetRoleByType((int)RoleCategory.CustomerRole);
            return View(role);
        }

        [HttpPost, MyAuthorize]
        public async Task<ActionResult> MerchantList(QueryDto query, int id = 1)
        {
            var service = GrainClient.GrainFactory.GetGrain<IUserSerive>("0");

            if (CurrentUser.Type == UserType.PlatformNormal || CurrentUser.Type == UserType.PlatformSuper)
            {
                ViewBag.IsShow = true;
                var data = await service.GetUserPage(null, UserType.CustomerSuper, query.SearchWord, query.timeBegin, query.timeEnd, (id - 1) * query.PageSize, query.PageSize);
                var list = new PagedList<UserOutPut>(data.Items, id, query.PageSize, data.TotalCount);
                if (Request.IsAjaxRequest())
                    return PartialView("_MerchantList", list);
                return View(list);
            }
            else
            {
                ViewBag.IsShow = false;
                var data = await service.GetUserPage(CurrentUser.MerchantId, UserType.CustomerNormal, query.SearchWord, query.timeBegin, query.timeEnd, (id - 1) * query.PageSize, query.PageSize);
                var list = new PagedList<UserOutPut>(data.Items, id, query.PageSize, data.TotalCount);
                if (Request.IsAjaxRequest())
                    return PartialView("_MerchantList", list);
                return View(list);
            }

        }
        /// <summary>
        /// 角色列表
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet, MyAuthorize]
        public async Task<ActionResult> RoleList(int pageSize = 10, int id = 1)
        {
            var service = GrainClient.GrainFactory.GetGrain<IRoleService>("0");
            var data = await service.GetPage(null, null, null, (id - 1) * 10, 10);
            var list = new PagedList<RoleInfo>(data.Items, id, pageSize, data.TotalCount);
            return View(list);

        }
        [HttpPost, MyAuthorize]
        public async Task<ActionResult> RoleList(QueryDto query, int id = 1)
        {
            var service = GrainClient.GrainFactory.GetGrain<IRoleService>("0");
            var data = await service.GetPage(query.SearchWord, query.timeBegin, query.timeBegin, (id - 1) * query.PageSize, query.PageSize);
            var list = new PagedList<RoleInfo>(data.Items, id, query.PageSize, data.TotalCount);
            if (Request.IsAjaxRequest())
                return PartialView("_RoleList", list);
            return View(list);
        }
        /// <summary>
        /// 上传二维码
        /// </summary>
        /// <returns></returns>
        public ActionResult UploadImage(long? accountId = null, string accountName = "")
        {
            if (accountId.HasValue)
            {
                ViewBag.Account = accountId;
                ViewBag.AccountName = accountName;
            }
            return View();
        }
        /// <summary>
        /// 支付宝账号list
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [MyAuthorize, HttpGet]
        public async Task<ActionResult> AliAccountList(int pageSize = 10, int id = 1)
        {
            var service = GrainClient.GrainFactory.GetGrain<IAliaccountService>("0");
            var data = await service.GetPage(null, CurrentUser.Id, null, null, (id - 1) * pageSize, pageSize);
            var list = new PagedList<AliAccountInfo>(data.Items, id, pageSize, data.TotalCount);
            ViewData["time"] = Config.GetValue("aliPayTime:offTime");
            return View(list);
        }
        [HttpPost]
        public async Task<ActionResult> AliAccountList(QueryDto query, int id = 1)
        {
            var service = GrainClient.GrainFactory.GetGrain<IAliaccountService>("0");
            var data = await service.GetPage(query.SearchWord, CurrentUser.Id, query.timeBegin, query.timeEnd, (id - 1) * query.PageSize, query.PageSize);
            var list = new PagedList<AliAccountInfo>(data.Items, id, query.PageSize, data.TotalCount);
            ViewData["time"] = Config.GetValue("aliPayTime:offTime");
            if (Request.IsAjaxRequest())
                return PartialView("_AliAccountList", list);
            return View(list);
        }
        /// <summary>
        /// 删除支付宝
        /// </summary>
        /// <param name="accountId"></param>
        /// <returns></returns>
        public async Task<ActionResult> AliAccountDelete(long accountId)
        {
            var service = GrainClient.GrainFactory.GetGrain<IAliaccountService>(CurrentUser.Id.ToString());
            var model = await service.GetAccountById(accountId);
            if (model != null)
            {
                await service.Delete(model);
                return Json(new { success = true, msg = "删除成功" });
            }
            else
            {
                return Json(new { success = false, msg = "请重试" });
            }
        }
        /// <summary>
        /// 禁用支付宝账号
        /// </summary>
        /// <param name="accountId"></param>
        /// <returns></returns>
        public async Task<ActionResult> StopAccount(long accountId)
        {
            var service = GrainClient.GrainFactory.GetGrain<IAliaccountService>(CurrentUser.Id.ToString());
            var model = await service.GetAccountById(accountId);
            model.IsEnable = false;
            model.ActiveTime = DateTime.Now;
            await service.Forbidden(model);
            return Json(new { success = true, msg = "停用成功" });
        }
        /// <summary>
        /// 启用支付宝账号
        /// </summary>
        /// <param name="accountId"></param>
        /// <returns></returns>
        public async Task<ActionResult> RestartAccount(long accountId)
        {
            var service = GrainClient.GrainFactory.GetGrain<IAliaccountService>(CurrentUser.Id.ToString());
            var model = await service.GetAccountById(accountId);
            model.IsEnable = true;
            await service.Forbidden(model);
            return Json(new { success = true, msg = "启用成功" });
        }

        /// <summary>
        /// 新增支付宝账号
        /// </summary>
        /// <param name="accountId"></param>
        /// <returns></returns>
        [HttpPost, MyAuthorize]
        public async Task<ActionResult> AddAccount(AliAccountInfo model)
        {
            var service = GrainClient.GrainFactory.GetGrain<IAliaccountService>(CurrentUser.Id.ToString());
            //是否包括别名
            var isContain = await service.IsContainSystemAccount(model.SystemAccount);
            if (isContain) return Json(new { success = false, msg = "系统账号已经被占用" });
            var info = new AliAccountInfo()
            {
                AccountName = model.AccountName,
                CreateTime = DateTime.Now,
                IsEnable = true,
                SystemAccount = model.SystemAccount,
                Pwd = PasswordHelper.Encoding(model.Pwd, 3)

            };
            await service.Add(info);

            return Json(new { success = true, msg = "新增成功" });
        }
        /// <summary>
        /// 新增支付宝账号
        /// </summary>
        /// <param name="accountId"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult AddAccount()
        {
            return View();

        }


        /// <summary>
        /// 新增角色
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult> AddRole()
        {
            var service = GrainClient.GrainFactory.GetGrain<IRoleService>("0");
            var data = await service.GetAllMenu();
            return View(data);
        }
        /// <summary>
        /// 新增角色
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> AddRole(RoleAddModel model)
        {
            if (model.MenuIds == null || model.MenuIds.Length == 0) return Json(new { success = false, msg = "请选择菜单" });
            var service = GrainClient.GrainFactory.GetGrain<IRoleService>("0");
            var role = new RoleInfo()
            {
                CreateTime = DateTime.Now,
                Description = model.Description,
                RoleName = model.RoleName,
                RoleType = model.RoleType
            };
            var id = await service.Add(role);

            foreach (var item in model.MenuIds)
            {
                var roleMenu = new RoleMenuInfo()
                {

                    MenuId = item,
                    RoleId = id
                };

                await service.Add(roleMenu);
            }
            return Json(new { success = true, msg = "添加成功" });
        }

        /// <summary>
        /// 删除role
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ActionResult> DeleteRole(long id)
        {
            var service = GrainClient.GrainFactory.GetGrain<IRoleService>("0");

            var success = await service.Delete(id);
            return Json(new { success = success, msg = "删除成功" });
        }
        /// <summary>
        /// 编辑角色
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult> EditRole(long roleId)
        {
            var service = GrainClient.GrainFactory.GetGrain<IRoleService>("0");
            var data = await service.GetAllMenu();
            var allHave = await service.GetMenuByRoleId(roleId);

            var role = await service.GetRoleById(roleId);
            ViewBag.Allhave = allHave;
            ViewBag.Id = roleId;
            ViewBag.Name = role.RoleName;
            ViewBag.Des = role.Description;
            return View(data);

        }
        /// <summary>
        /// 编辑角色
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> EditRole(RoleAddModel model)
        {
            if (model.MenuIds == null || model.MenuIds.Length == 0) return Json(new { success = false, msg = "请选择菜单" });
            var service = GrainClient.GrainFactory.GetGrain<IRoleService>("0");
            //更新role
            var role = await service.GetRoleById(model.RoleId);
            role.RoleName = model.RoleName;
            role.Description = model.Description;
            await service.Update(role);

            await service.DeleteMenuByRoleId(model.RoleId);
            foreach (var item in model.MenuIds)
            {
                var roleMenu = new RoleMenuInfo()
                {

                    MenuId = item,
                    RoleId = model.RoleId
                };

                await service.Add(roleMenu);
            }
            return Json(new { success = true, msg = "编辑成功" });
        }
        /// <summary>
        /// 二维码列表get
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult> QRCodeList(int pageSize = 10, int id = 1)
        {
            var aliAccount = Request["aliAccount"];
            var service = GrainClient.GrainFactory.GetGrain<IQRCodeService>("0");
            var data = await service.GetPage(aliAccount, null, null, (id - 1) * pageSize, pageSize);
            var list = new PagedList<QRCodeOutPut>(data.Items, id, pageSize, data.TotalCount);
            return View(list);
        }
        /// <summary>
        /// 二维码列表 post
        /// </summary>
        /// <param name="query"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> QRCodeList(int id = 1)
        {
            var aliAccount = Request["aliAccount"];
            var service = GrainClient.GrainFactory.GetGrain<IQRCodeService>("0");
            var data = await service.GetPage(aliAccount, null, null, (id - 1) * 10, 10);
            var list = new PagedList<QRCodeOutPut>(data.Items, id, 10, data.TotalCount);
            if (Request.IsAjaxRequest())
                return PartialView("_QRCodeList", list);
            return View(list);
        }

        /// <summary>
        /// 删除二维码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ActionResult> QRCodeDelete(long id)
        {
            var service = GrainClient.GrainFactory.GetGrain<IQRCodeService>("0");
            var info = await service.GetById(id);
            if (info == null) throw new LotException("没有对应二维码");
            var success = await service.Delete(info);
            var msg = success == true ? "删除成功" : "删除失败";
            return Json(new { success = success, msg = msg });
        }
        /// <summary>
        /// 订单列表
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult> OrderList(int pageSize = 10, int id = 1)
        {
            var service = GrainClient.GrainFactory.GetGrain<IOrderService>("0");
            if (CurrentUser.Type == UserType.PlatformSuper || CurrentUser.Type == UserType.PlatformNormal)
            {
                var data = await service.GetPage(null, null, null, null, (id - 1) * pageSize, pageSize);
                var list = new PagedList<OrderInfo>(data.Items, id, pageSize, data.TotalCount);
                return View(list);
            }
            else
            {
                var data = await service.GetPage(null, CurrentUser.MerchantId, null, null, (id - 1) * pageSize, pageSize);
                var list = new PagedList<OrderInfo>(data.Items, id, pageSize, data.TotalCount);
                return View(list);
            }


        }
        /// <summary>
        /// 订单列表
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="id"></param>
        [HttpPost]
        public async Task<ActionResult> OrderList(QueryDto query, int id = 1)
        {
            var service = GrainClient.GrainFactory.GetGrain<IOrderService>("0");
            if (CurrentUser.Type == UserType.PlatformSuper || CurrentUser.Type == UserType.PlatformNormal)
            {
                var data = await service.GetPage(query.SearchWord, null, query.timeBegin, query.timeEnd, (id - 1) * query.PageSize, query.PageSize);
                var list = new PagedList<OrderInfo>(data.Items, id, query.PageSize, data.TotalCount);
                if (Request.IsAjaxRequest())
                    return PartialView("_orderList", list);
                return View(list);
            }
            else
            {
                var data = await service.GetPage(query.SearchWord, CurrentUser.MerchantId, query.timeBegin, query.timeEnd, (id - 1) * query.PageSize, query.PageSize);
                var list = new PagedList<OrderInfo>(data.Items, id, query.PageSize, data.TotalCount);
                if (Request.IsAjaxRequest())
                    return PartialView("_orderList", list);
                return View(list);
            }


        }
        /// <summary>
        /// 订单统计列表
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult> OrderStatisticList(int pageSize = 10, int id = 1)
        {
            var service = GrainClient.GrainFactory.GetGrain<IOrderService>("0");
            if (CurrentUser.Type == UserType.PlatformSuper || CurrentUser.Type == UserType.PlatformNormal)
            {
                var data = await service.GetPageStatistic(null, null, null, null, (id - 1) * pageSize, pageSize);
                var list = new PagedList<StatisticModel>(data.Items, id, pageSize, data.TotalCount);
                return View(list);
            }
            else
            {
                var data = await service.GetPageStatistic(null, CurrentUser.MerchantId, null, null, (id - 1) * pageSize, pageSize);
                var list = new PagedList<StatisticModel>(data.Items, id, pageSize, data.TotalCount);
                return View(list);
            }
        }

        /// <summary>
        /// 订单统计列表
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="id"></param>
        [HttpPost]
        public async Task<ActionResult> OrderStatisticList(QueryDto query, int id = 1)
        {
            var service = GrainClient.GrainFactory.GetGrain<IOrderService>("0");
            if (CurrentUser.Type == UserType.PlatformSuper || CurrentUser.Type == UserType.PlatformNormal)
            {
                var data = await service.GetPageStatistic(query.SearchWord, null, query.timeBegin, query.timeEnd, (id - 1) * query.PageSize, query.PageSize);
                var list = new PagedList<StatisticModel>(data.Items, id, query.PageSize, data.TotalCount);
                if (Request.IsAjaxRequest())
                    return PartialView("_orderStatisticList", list);
                return View(list);
            }
            else
            {
                var data = await service.GetPageStatistic(query.SearchWord, CurrentUser.MerchantId, query.timeBegin, query.timeEnd, (id - 1) * query.PageSize, query.PageSize);
                var list = new PagedList<StatisticModel>(data.Items, id, query.PageSize, data.TotalCount);
                if (Request.IsAjaxRequest())
                    return PartialView("_orderStatisticList", list);
                return View(list);
            }


        }

        /// <summary>
        /// 提现申请
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult> ApplyCash()
        {
            var service = GrainClient.GrainFactory.GetGrain<IApplyService>("0");
            if (CurrentUser.Type == UserType.PlatformSuper || CurrentUser.Type == UserType.PlatformNormal)
            {
                return View();
            }
            var info = await service.GetByMerchantId(CurrentUser.MerchantId);

            return View(info);
        }


        /// <summary>
        /// 提现申请
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> ApplyCash(ApplyInput input)
        {
            var service = GrainClient.GrainFactory.GetGrain<IApplyService>(CurrentUser.Id.ToString());
            var serviceAli = GrainClient.GrainFactory.GetGrain<IMerchantService>(CurrentUser.Id.ToString());
            var info = await service.GetByMerchantId(CurrentUser.MerchantId);
            if (input.ApplyAmount > info.TotalAmount) return Json(new { success = false, msg = "不能大于可用余额" });

            using (var tran = WorkManager.BeginTransaction())
            {
                ApplyInfo model = new ApplyInfo()
                {

                    ApplyAmount = input.ApplyAmount,
                    CreateTime = DateTime.Now,
                    MerchantId = input.Id,
                    Status = ApplyStatus.WaitPass,
                    MerName = CurrentUser.UserName,
                     BankCard=input.BankCard
                };
                //减去可用余额
                var merchantInfo = await serviceAli.GetById(input.Id);
                if (merchantInfo == null) throw new LotException("没有此商户");
                var temp = merchantInfo.TotalAmount - input.ApplyAmount;
                merchantInfo.TotalAmount = temp;
                await serviceAli.Update(merchantInfo);
                await service.Add(model);
                tran.Complete();
            }

              
            return Json(new { success = true, msg = "申请成功" });
        }
        /// <summary>
        /// 提现申请列表
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult> ApplyList(int pageSize = 10, int id = 1)
        {
            var service = GrainClient.GrainFactory.GetGrain<IApplyService>("0");
            if (CurrentUser.Type == UserType.PlatformSuper || CurrentUser.Type == UserType.PlatformNormal)
            {
                ViewBag.IsShow = true;
                var data = await service.GetPage(null, null, null, (id - 1) * pageSize, pageSize);
                var list = new PagedList<ApplyInfo>(data.Items, id, pageSize, data.TotalCount);
                return View(list);
            }
            else
            {
                ViewBag.IsShow = false;
                var data = await service.GetPage(CurrentUser.MerchantId, null, null, (id - 1) * pageSize, pageSize);
                var list = new PagedList<ApplyInfo>(data.Items, id, pageSize, data.TotalCount);
                return View(list);
            }
        }
        /// <summary>
        /// 提现申请列表
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> ApplyList(QueryDto query, int id = 1)
        {
            var service = GrainClient.GrainFactory.GetGrain<IApplyService>("0");

            if (CurrentUser.Type == UserType.PlatformSuper || CurrentUser.Type == UserType.PlatformNormal)
            {
                ViewBag.IsShow = true;
                var data = await service.GetPage(null, query.timeBegin, query.timeEnd, (id - 1) * query.PageSize, query.PageSize);
                var list = new PagedList<ApplyInfo>(data.Items, id, query.PageSize, data.TotalCount);
                if (Request.IsAjaxRequest())
                    return PartialView("_ApplyList", list);
                return View(list);
            }
            else
            {
                ViewBag.IsShow = false;
                var data = await service.GetPage(CurrentUser.MerchantId, query.timeBegin, query.timeEnd, (id - 1) * query.PageSize, query.PageSize);
                var list = new PagedList<ApplyInfo>(data.Items, id, query.PageSize, data.TotalCount);
                if (Request.IsAjaxRequest())
                    return PartialView("_ApplyList", list);
                return View(list);
            }
        }
        /// <summary>
        /// 审批
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult> ApplyCheck(long id)
        {
            var service = GrainClient.GrainFactory.GetGrain<IApplyService>("0");
            var info = await service.GetById(id);
            if (info == null) { return Json(new { success = false, msg = "提现申请不存在" }); };
            return View(info);
        }

        /// <summary>
        /// 审批
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> ApplyCheck(ApplyInfo model)
        {
            var service = GrainClient.GrainFactory.GetGrain<IApplyService>("0");
            var info = await service.GetById(model.Id);
            if (info == null) { return Json(new { success = false, msg = "提现申请不存在" }); };
            string mark = Request["pass"];
            if (mark.Equals("通过"))
            {
                info.Status = ApplyStatus.Pass;
                await service.Update(info);
                return Json(new { success = true, msg = "审批成功" });
            }
            else
            {
                if (info.Status == ApplyStatus.UnPass) { return Json(new { success = false, msg = "不能重复操作" }); }
                info.Status = ApplyStatus.UnPass;
                var serviceMer = GrainClient.GrainFactory.GetGrain<IMerchantService>("0");
                var merInfo= await serviceMer.GetById(model.MerchantId);
                if (merInfo == null) throw new LotException("商户不存在");

             
                merInfo.TotalAmount = merInfo.TotalAmount + info.ApplyAmount;
                await serviceMer.Update(merInfo);
                await service.Update(info);
                return Json(new { success = true, msg = "驳回成功" });
            }
        }
        /// <summary>
        /// 冻结资金
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult> FreezeMoney(long id)
        {
            var service = GrainClient.GrainFactory.GetGrain<IMerchantService>("0");
            var info = await service.GetById(id);
            if (info == null) throw new LotException("商户不存在");
            return View(info);
        }
        /// <summary>
        /// 冻结资金
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> FreezeMoney(long id, decimal freezeMoney)
        {
            var service = GrainClient.GrainFactory.GetGrain<IMerchantService>("0");

            var info = await service.GetById(id);
            if (info == null) throw new LotException("商户不存在");
            if (freezeMoney > info.TotalAmount || freezeMoney <= 0) return Json(new { success = false, msg = "冻结金额不能大于可用金额" });
            using (var tran = WorkManager.BeginTransaction())
            {
                info.TotalAmount = info.TotalAmount - freezeMoney;
                info.FreezeAmount = freezeMoney;
                await service.Update(info);
            }

            return Json(new { success = true, msg = "冻结成功" });

        }
        /// <summary>
        /// 解冻资金
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult> UnFreezeMoney(long id)
        {
            var service = GrainClient.GrainFactory.GetGrain<IMerchantService>("0");
            var info = await service.GetById(id);
            if (info == null) throw new LotException("商户不存在");
            return View(info);
        }
        /// <summary>
        /// 解冻资金
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> UnFreezeMoney(long id, decimal unFreezeMoney)
        {
            var service = GrainClient.GrainFactory.GetGrain<IMerchantService>("0");

            var info = await service.GetById(id);
            if (info == null) throw new LotException("商户不存在");
            if (unFreezeMoney > info.FreezeAmount|| unFreezeMoney<=0) return Json(new { success = false, msg = "冻结金额不能大于可用金额且必须大于0" });
            using (var tran = WorkManager.BeginTransaction())
            {
                info.TotalAmount = info.TotalAmount +unFreezeMoney;
                info.FreezeAmount = info.FreezeAmount - unFreezeMoney;
                await service.Update(info);
            }

            return Json(new { success = true, msg = "解冻成功" });

        }
      
    }
}